package com.example.apiproject.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class IMserver {

    public static final Map<String, Channel> USERS = new ConcurrentHashMap<>(1024);
    public static final Map<String, ChannelGroup>  GROUP = new ConcurrentHashMap<>(1024);

    public static void start() {
        // 创建接收客户端请求连接的事件处理器
        EventLoopGroup boss = new NioEventLoopGroup();
        // 创建处理已接受连接的事件处理器
        EventLoopGroup worker = new NioEventLoopGroup();

        // 创建netty服务
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, worker)
                // 设置NIO 模式
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 设置执行链
                        ChannelPipeline  pipline = socketChannel.pipeline();
                        // 添加http编码解码器到执行链
                        pipline.addLast(new HttpServerCodec())
                                // 支持大数据流
                                .addLast(new ChunkedWriteHandler())
                                // 对http消息聚合。FullHttpRequest、FullHttpResponse
                                .addLast(new HttpObjectAggregator(1024 * 64))
                                // websocket
                                .addLast(new WebSocketServerProtocolHandler("/"))
                                .addLast(new WebsocketHandler());
                    }
                });
        ChannelFuture channelFuture = null;
        try{
            channelFuture = bootstrap.bind(8085).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e){
            throw new RuntimeException(e);
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }
}
